import { type IDomEditor, type SlateDescendant, type SlateElement } from '@wangeditor/editor'

/**
 * 解析 HTML 字符串
 * @param domElem HTML 对应的 DOM Element
 * @param children 子节点
 * @param editor editor 实例
 * @returns 自定义元素
 */
function parseTitleBlackHtml(domElem: Element, children: SlateDescendant[], editor: IDomEditor): SlateElement {  // TS 语法
    // 从 HTML 中提取标题
    const titleElement = domElem.querySelector('div[style*="font-size: 18px"]')
    const title = titleElement?.textContent || ''

    // 从 HTML 中提取描述
    const descElement = domElem.querySelector('p[style*="font-size: 16px"]')
    const description = descElement?.textContent || ''

    // 从 HTML 中提取图片 URL
    const imgElement = domElem.querySelector('img')
    const imageUrl = imgElement?.src || ''

    // 从 HTML 中提取链接 URL
    const buttonElement = domElem.querySelector('button[onclick]')
    const linkUrl = buttonElement?.getAttribute('onclick')?.match(/window\.open\('([^']+)'/)?.[1] || ''

    // 从 HTML 中提取服务名称、工作性质和薪资范围
    // 通过遍历所有包含 display: flex 的 div 元素来找到对应的字段
    const flexDivs = domElem.querySelectorAll('div[style*="display: flex"]')
    let serviceName = ''
    let jobNature = ''
    let salaryRange = ''

    flexDivs.forEach(div => {
        const spans = div.querySelectorAll('span')
        if (spans.length >= 2) {
            const firstSpan = spans[0]
            const secondSpan = spans[1]

            // 根据第一个 span 的内容（图标）来确定是哪个字段
            if (firstSpan.textContent?.includes('🕐')) {
                serviceName = secondSpan.textContent || ''
            } else if (firstSpan.textContent?.includes('💻')) {
                jobNature = secondSpan.textContent || ''
            } else if (firstSpan.textContent?.includes('💰')) {
                salaryRange = secondSpan.textContent || ''
            }
        }
    })

    const myResume = {
        type: 'title-black',
        title: title,
        description: description,
        imageUrl: imageUrl,
        linkUrl: linkUrl,
        serviceName: serviceName,
        jobNature: jobNature,
        salaryRange: salaryRange,
        children: [{ text: '' }]
    }

    return myResume
}

export const parseHtmlConf = {
    selector: 'div[data-w-e-type="title-black"]', // data-w-e-type 属性，留给自定义元素，保证扩展性
    parseElemHtml: parseTitleBlackHtml,
}